package org.seven.jrdp.commons.shiro.session;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisOperations;

public class RedisSessionDAO extends AbstractSessionDAO {
	private static final String CACHE_KEY = RedisSessionDAO.class.getSimpleName();

	@SuppressWarnings("rawtypes")
	private RedisOperations redisOperations;

	@SuppressWarnings("rawtypes")
	public void setRedisOperations(RedisOperations redisOperations) {
		this.redisOperations = redisOperations;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		redisOperations.opsForHash().put(CACHE_KEY, sessionId, session);
		return sessionId;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Session doReadSession(Serializable sessionId) {
		return (Session) redisOperations.opsForHash().get(CACHE_KEY, sessionId);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void update(Session session) throws UnknownSessionException {
		redisOperations.opsForHash().put(CACHE_KEY, session.getId(), session);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void delete(Session session) {
		redisOperations.opsForHash().delete(CACHE_KEY, session.getId());
	}

	@Override
	@SuppressWarnings("unchecked")
	public Collection<Session> getActiveSessions() {
		return redisOperations.opsForHash().values(CACHE_KEY);
	}
}